define([
  'jquery',
  'GlobalInfo',
  'Grid',
  'bootstrap',
  'navBar-general',
  'jquery-ui.min'
],
function ($, GlobalInfo, Grid) {
  GlobalInfo.BlockUI("Cargando...");
  $(function(){
      GlobalInfo.CheckSession();
      var roleId = 0;
      var roles = null;
	  var columnNames= null;
      var params = {
        sessionUUID: GlobalInfo.sessionUUID,
        roleNameFilter: ''
      };

      GlobalInfo.CallWebService('RoleServices', 
                                'GetAllRoles', 
                                params, 
                                GetAllRolesSuccessCallback,
                                GetAllRolesErrorCallback);
      
      $("#cancel").click(function(){
        CloseDialog();
      });

      $("#newuser").click(function(){
        OpenDialog();
      });

      $("#yes").click(function() {
        var params = {
          sessionUUID: GlobalInfo.sessionUUID,
          roleId: roleId
        }

        GlobalInfo.CallWebService('RoleServices', 
                                  'DeleteRole', 
                                  params, 
                                  DeleteRoleSuccessCallback, 
                                  DeleteRoleErrorCallback);
      });

      $("#no").click(function() {
        $("#deleteDialog").dialog("close");
      });

      $("#save").click(function() {
        var roleName = $('#Name').val();
        var permissions = "";
        var isActive = false;
        var selects;
        var params;

        
        if(roleName == null || roleName.trim().length == 0 || roleName == ""){
          GlobalInfo.DialogShowMessage("Tiene que ingresar un nombre para el rol.", true, 5000);
          return;
        }

        selects = $('#dialog > span > select');
        
        for(var i = 0; i < selects.length; i++){
          permissions += selects[i].id + ":" + selects[i].options[selects[i].selectedIndex].value + '|';
        }

        permissions = permissions.substring(0, permissions.length - 1);
        isActive = $('#Activo').is(':checked');
        
        params = {
          sessionUUID: GlobalInfo.sessionUUID,
          roleId: roleId,
          Name: roleName,
          Permissions: permissions,
          enabled: isActive
        }

        GlobalInfo.CallWebService('RoleServices', 
                                  'SaveRole', 
                                  params, 
                                  SaveRoleSuccessCallback, 
                                  SaveRoleErrorCallback);
      });

      function GetAllRolesSuccessCallback(resultObj){
        if(resultObj.error() != null){
          GlobalInfo.ShowMessage(resultObj.error(), true, 0);
        }
        else{
            roles = resultObj.result().Role;

            var grid = new Grid(roles);
      		columnNames= [{label:"Nombre", value:"Name"},
                        {label:"Fecha de creaci&oacute;n",value:"CreationDateStr"},
                        {label:"Ultima actualizaci&oacute;n",value:'LastUpdateDateStr'},
                        {label:"Acciones",value:"Action"}];
    		grid.clear();
    		  
            var buttons = [];
            var editButton = $('<button />')
                                .text('Editar')
        					    .attr('id','edit')
                                .attr('name','edit')
                                .addClass('btn')
                                .click(
                                  function(){
                                    var selectedObj = grid.dataSource[grid.selectedIndex];

                                    if(typeof GlobalInfo.roleId != 'undefined' && GlobalInfo.roleId == selectedObj.RoleId){
                                        $('<div></div>')
                                        .appendTo('body')
                                        .html('<div><h6>Si modifica este rol su sesión será terminada</h6></div>')
                                        .dialog({
                                            modal: true, title: 'Confirmación', zIndex: 10000, autoOpen: true,
                                            width: 'auto', resizable: false,
                                            buttons: {
                                                Ok: function () {
                                                    OpenDialog(selectedObj);
                                                    $(this).dialog("close");
                                                },
                                                Cancelar: function () {
                                                    $(this).dialog("close");
                                                }
                                            },
                                            close: function (event, ui) {
                                                $(this).remove();
                                            }
                                        });
                                    }         
                                    else{
                                        OpenDialog(selectedObj);
                                    }                           
                                  });

            var deleteButton = $('<button />')
                                .text('Borrar')
        					    .attr('id',"delete")
                                .attr('name',"delete")
                                .addClass('btn btn-danger')
                                .click(
                                  function(){
                                    var selectedObj = grid.dataSource[grid.selectedIndex];
                                    roleId = selectedObj.RoleId;

                                    if(typeof GlobalInfo.roleId != 'undefined' && GlobalInfo.roleId == selectedObj.RoleId){
                                        $('<div></div>')
                                        .appendTo('body')
                                        .html('<div><h6>Si elimina este rol su sesión será terminada</h6></div>')
                                        .dialog({
                                            modal: true, title: 'Confirmación', zIndex: 10000, autoOpen: true,
                                            width: 'auto', resizable: false,
                                            buttons: {
                                                Ok: function () {
                                                    $('#deleteMessage').text("Está seguro de que desea eliminar el rol: " + selectedObj.Name);
                                                    $("#deleteDialog").dialog({
                                                        dialogClass: "no-close",
                                                        modal: "true",
                                                        width:  350,
                                                        height: 150,
                                                        position: 'center'
                                                    });
                                                    $(this).dialog("close");
                                                },
                                                Cancelar: function () {
                                                    $(this).dialog("close");
                                                }
                                            },
                                            close: function (event, ui) {
                                                $(this).remove();
                                            }
                                        });
                                    }         
                                    else{
                                        $('#deleteMessage').text("Está seguro de que desea eliminar el rol: " + selectedObj.Name);
                                        $("#deleteDialog").dialog({
                                            dialogClass: "no-close",
                                            modal: "true",
                                            width:  350,
                                            height: 150,
                                            position: 'center'
                                        });
                                    }   
                                });

            buttons.push(editButton);
            buttons.push(deleteButton);

            grid.createGrid(columnNames, buttons);
            grid.excludeColumn("Action", FilterStatic);
        }
        GlobalInfo.UnblockUI();
      }
		
      function GetAllRolesErrorCallback(error){
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
      }

      function SaveRoleSuccessCallback(resultObj){ 
        if(GlobalInfo.roleId == roleId){
            GlobalInfo.Logout();
        }
        else{

            if(resultObj.error() != null){
              GlobalInfo.ShowMessage(resultObj.error(), true, 5000);
            }
            else{
              var params = {
                  sessionUUID: GlobalInfo.sessionUUID,
                  roleNameFilter: ''
                };
              GlobalInfo.ShowMessage('Se ha guardado el rol correctamente', false, 5000);
              GlobalInfo.CallWebService('RoleServices', 
                                        'GetAllRoles', 
                                        params, 
                                        GetAllRolesSuccessCallback,
                                        GetAllRolesErrorCallback);
            }
            CloseDialog();
        }
      }

      function SaveRoleErrorCallback(error){
        CloseDialog();
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
      }

      function DeleteRoleSuccessCallback(resultObj){ 
        if(GlobalInfo.roleId == roleId){
            GlobalInfo.Logout();
        }
        else{
            if(resultObj.error() != null){
              GlobalInfo.ShowMessage(resultObj.error(), true, 5000);
            }
            else{
              var params = {
                  sessionUUID: GlobalInfo.sessionUUID,
                  roleNameFilter: ''
                };
              GlobalInfo.CallWebService('RoleServices', 
                                        'GetAllRoles', 
                                        params, 
                                        GetAllRolesSuccessCallback,
                                        GetAllRolesErrorCallback);
            }
            $("#deleteDialog").dialog("close");
        }
      }

      function DeleteRoleErrorCallback(error){
        $("#deleteDialog").dialog("close");
        GlobalInfo.ShowMessage('Ocurrió un error inesperado. Por favor intente más tarde.', true, 5000);
      }

      function OpenDialog(selectedObj){
        if(typeof selectedObj != "undefined" && selectedObj != null){
          //Fill dialog data
          $('#Name').val(selectedObj.Name);

          for(var i = 0; i < selectedObj.Permissions.RoleDet.length; i++){
            var permission = selectedObj.Permissions.RoleDet[i];
            $('#' + permission.Resource).val(permission.AccessLevel);
          }

          $('input[name=Activo]').attr('checked', (typeof selectedObj.IsActive != "undefined" && selectedObj.IsActive != null && selectedObj.IsActive == "true"));
        
          roleId = selectedObj.RoleId;
        }
        else{
          //Clear dialog data
          $('#Name').val("");
          $('input[name=Activo]').attr('checked', true);
          roleId = 0;
        }
          $("#dialog").dialog({
              dialogClass: "no-close",
              modal: "true",
              width:  750,
              height: 500,
              position: 'center'
          });
      }

      function CloseDialog(){
        $("#dialog").dialog("close");
      }

      function FilterStatic(obj){
        return obj.IsStatic == true || obj.IsStatic == 1 || obj.IsStatic == "true";
      }
  });
});